//
//  GJUtil.m
//  xmgjAppFront
//
//  Created by Zeki on 2020/7/9.
//  Copyright © 2020 guojutech. All rights reserved.
//

#import "GJUtil.h"
#import <sys/utsname.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>


//获取网关信息
#import <arpa/inet.h>
#import <netinet/in.h>
#import <ifaddrs.h>
#import "getgateway.h"

#import "GJKeyChainManager.h"

#define KEY_UUID_DATA @"net.guojutech.app"
#define KEY_UUID_TEXT @"UUID_TEXT"

@implementation GJUtil
+(void)checkVersion:(void (^)(BOOL))showToaskBlock{
  [[GJNetWork sharedInstance] getWithURL:GJVersionCheck params:@{@"appName":[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"] ,@"type":@"ios"} success:^(GJResponse * _Nonnull response) {
    NSString *localVersion = [UIApplication sharedApplication].appVersion;
    NSArray *localArray = [localVersion componentsSeparatedByString:@"."];
    NSDictionary *data = response.data;
    NSString *number = [NSString stringWithFormat:@"%@", data[@"versionName"]];
    NSString *deployNote = data[@"deployNote"];
    NSArray *numberArray = [number componentsSeparatedByString:@"."];
    __block BOOL isShowAlert = NO;
    
    for (int i = 0; i < (numberArray.count >= localArray.count ? localArray.count : numberArray.count ); i ++) {
      NSString * obj = [localArray objectAtIndex:i];
      NSString *numTemp = [numberArray objectAtIndex:i];
      if ([numTemp integerValue] > [obj integerValue]) {
        isShowAlert = YES;
        break;
      }else if ([obj integerValue] > [numTemp integerValue]) {
        isShowAlert = NO;
        break;
      }
    }
    
    NSString *cancelTitle = @"取消";
    if (isShowAlert) {
      NSInteger mustUpdate = [data[@"mustUpdate"] integerValue];
      if (mustUpdate) {
        cancelTitle = @"";
      }
      UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"本次升级说明" message:deployNote preferredStyle:(UIAlertControllerStyleAlert)];
      NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
      paraStyle.alignment = NSTextAlignmentLeft;
      NSMutableAttributedString *atrStr = [[NSMutableAttributedString alloc] initWithString:deployNote attributes:@{NSParagraphStyleAttributeName:paraStyle,NSFontAttributeName:[UIFont systemFontOfSize:13.0]}];
      
      [alert setValue:atrStr forKey:@"attributedMessage"];
      UIAlertAction *action = [UIAlertAction actionWithTitle:@"去App Store下载" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        //跳转app Store
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:GJAPPDownloadURL]];
        exit(0);
      }];
      [alert addAction:action];
      if ([cancelTitle gj_hasValue]) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
  
        }];
        [alert addAction:action];
      }
      [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
    }else{
      if (showToaskBlock) {
        showToaskBlock(YES);
      }
    }
  } failure:^(NSString * _Nonnull errorMessage) {
    [UIAlertController showAlertInViewController:[UIApplication sharedApplication].keyWindow.rootViewController
                                       withTitle:@"温馨提示"
                                         message:@"连接服务器失败，请确认网络连接后重启应用"
                               cancelButtonTitle:nil
                          destructiveButtonTitle:@"确定"
                               otherButtonTitles:nil
                                        tapBlock:^(UIAlertController * _Nonnull controller, UIAlertAction * _Nonnull action, NSInteger buttonIndex)
     {
      if (buttonIndex == controller.destructiveButtonIndex) {
        //跳转app Store
        exit(0);
      }
    }];
  }];
}

+ (void)openURLMapNavgationLocation:(CLLocationCoordinate2D)location{
  @weakify(self);
  [UIAlertController showActionSheetInViewController:[UIApplication sharedApplication].keyWindow.rootViewController
                                           withTitle:nil
                                             message:nil
                                   cancelButtonTitle:@"取消"
                              destructiveButtonTitle:nil
                                   otherButtonTitles:[NSArray getInstalledMapAppTitles]
                  popoverPresentationControllerBlock:nil
                                            tapBlock:^(UIAlertController * _Nonnull controller, UIAlertAction * _Nonnull action, NSInteger buttonIndex) {
    NSInteger firstOtherIndex = controller.firstOtherButtonIndex;
    if (buttonIndex == firstOtherIndex) {
      [GJUtil navAppleMapLocation:location];
    } else if (buttonIndex == controller.cancelButtonIndex ||
               buttonIndex == controller.destructiveButtonIndex) {
    } else {
      NSArray *array = [NSArray getInstalledMapAppWithEndLocation:location];
      NSString *url = array[buttonIndex-firstOtherIndex][@"url"];
      [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }
  }];
}
//苹果地图
+ (void)navAppleMapLocation:(CLLocationCoordinate2D)location {
  // 转为百度经纬度类型的坐标
  //  location = BMKCoordTrans(location,BMK_COORDTYPE_BD09LL,BMK_COORDTYPE_COMMON);
  MKMapItem *currentLoc = [MKMapItem mapItemForCurrentLocation];
  MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:location
                                                                                     addressDictionary:nil]];
  toLocation.name = @"";
  
  NSArray *items = @[currentLoc, toLocation];
  NSDictionary *dic = @{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving,
                        MKLaunchOptionsMapTypeKey : @(MKMapTypeStandard),
                        MKLaunchOptionsShowsTrafficKey : @(YES)};
  
  [MKMapItem openMapsWithItems:items launchOptions:dic];
}


+ (BOOL)hasLocationAuthorization {
  CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
  
  if ([CLLocationManager locationServicesEnabled] &&
      (status == kCLAuthorizationStatusAuthorizedWhenInUse ||
       status == kCLAuthorizationStatusAuthorizedAlways)) {
    return YES;
  }
  return NO;
}

+ (NSString *)currentModel {
  struct utsname systemInfo;
  uname(&systemInfo);
  NSString *phoneModel = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
  
  if ([phoneModel isEqualToString:@"iPhone1,1"])    return @"Apple#iPhone 1G";
  if ([phoneModel isEqualToString:@"iPhone1,2"])    return @"Apple#iPhone 3G";
  if ([phoneModel isEqualToString:@"iPhone2,1"])    return @"Apple#iPhone 3GS";
  if ([phoneModel isEqualToString:@"iPhone3,1"])    return @"Apple#iPhone 4";
  if ([phoneModel isEqualToString:@"iPhone3,2"])    return @"Apple#iPhone 4 Verizon";
  if ([phoneModel isEqualToString:@"iPhone4,1"])    return @"Apple#iPhone 4S";
  if ([phoneModel isEqualToString:@"iPhone5,2"])    return @"Apple#iPhone 5";
  if ([phoneModel isEqualToString:@"iPhone5,3"])    return @"Apple#iPhone 5c";
  if ([phoneModel isEqualToString:@"iPhone5,4"])    return @"Apple#iPhone 5c";
  if ([phoneModel isEqualToString:@"iPhone6,1"])    return @"Apple#iPhone 5s";
  if ([phoneModel isEqualToString:@"iPhone6,2"])    return @"Apple#iPhone 5s";
  if ([phoneModel isEqualToString:@"iPhone7,1"])    return @"Apple#iPhone 6 Plus";
  if ([phoneModel isEqualToString:@"iPhone7,2"])    return @"Apple#iPhone 6";
  if ([phoneModel isEqualToString:@"iPhone8,1"])    return @"Apple#iPhone 6s";
  if ([phoneModel isEqualToString:@"iPhone8,2"])    return @"Apple#iPhone 6s Plus";
  if ([phoneModel isEqualToString:@"iPhone8,4"])    return @"Apple#iPhone SE";
  if ([phoneModel isEqualToString:@"iPhone9,1"])    return @"Apple#iPhone 7";
  if ([phoneModel isEqualToString:@"iPhone9,2"])    return @"Apple#iPhone 7 Plus";
  if ([phoneModel isEqualToString:@"iPhone9,3"])    return @"Apple#iPhone 7";
  if ([phoneModel isEqualToString:@"iPhone9,4"])    return @"Apple#iPhone 7 Plus";
  if ([phoneModel isEqualToString:@"iPhone10,1"])   return @"Apple#iPhone 8 Global";
  if ([phoneModel isEqualToString:@"iPhone10,2"])   return @"Apple#iPhone 8 Plus Global";
  if ([phoneModel isEqualToString:@"iPhone10,3"])   return @"Apple#iPhone X Global";
  if ([phoneModel isEqualToString:@"iPhone10,4"])   return @"Apple#iPhone 8 GSM";
  if ([phoneModel isEqualToString:@"iPhone10,5"])   return @"Apple#iPhone 8 Plus GSM";
  if ([phoneModel isEqualToString:@"iPhone10,6"])   return @"Apple#iPhone X GSM";
  
  if ([phoneModel isEqualToString:@"iPhone11,2"])   return @"Apple#iPhone XS";
  if ([phoneModel isEqualToString:@"iPhone11,4"])   return @"Apple#iPhone XS Max (China)";
  if ([phoneModel isEqualToString:@"iPhone11,6"])   return @"Apple#iPhone XS Max";
  if ([phoneModel isEqualToString:@"iPhone11,8"])   return @"Apple#iPhone XR";
  
  if ([phoneModel isEqualToString:@"i386"])         return @"Apple#Simulator 32";
  if ([phoneModel isEqualToString:@"x86_64"])       return @"Apple#Simulator 64";
  
  if ([phoneModel isEqualToString:@"iPad1,1"]) return @"iPad";
  if ([phoneModel isEqualToString:@"iPad2,1"] ||
      [phoneModel isEqualToString:@"iPad2,2"] ||
      [phoneModel isEqualToString:@"iPad2,3"] ||
      [phoneModel isEqualToString:@"iPad2,4"]) return @"iPad 2";
  if ([phoneModel isEqualToString:@"iPad3,1"] ||
      [phoneModel isEqualToString:@"iPad3,2"] ||
      [phoneModel isEqualToString:@"iPad3,3"]) return @"iPad 3";
  if ([phoneModel isEqualToString:@"iPad3,4"] ||
      [phoneModel isEqualToString:@"iPad3,5"] ||
      [phoneModel isEqualToString:@"iPad3,6"]) return @"iPad 4";
  if ([phoneModel isEqualToString:@"iPad4,1"] ||
      [phoneModel isEqualToString:@"iPad4,2"] ||
      [phoneModel isEqualToString:@"iPad4,3"]) return @"iPad Air";
  if ([phoneModel isEqualToString:@"iPad5,3"] ||
      [phoneModel isEqualToString:@"iPad5,4"]) return @"iPad Air 2";
  if ([phoneModel isEqualToString:@"iPad6,3"] ||
      [phoneModel isEqualToString:@"iPad6,4"]) return @"iPad Pro 9.7-inch";
  if ([phoneModel isEqualToString:@"iPad6,7"] ||
      [phoneModel isEqualToString:@"iPad6,8"]) return @"iPad Pro 12.9-inch";
  if ([phoneModel isEqualToString:@"iPad6,11"] ||
      [phoneModel isEqualToString:@"iPad6,12"]) return @"iPad 5";
  if ([phoneModel isEqualToString:@"iPad7,1"] ||
      [phoneModel isEqualToString:@"iPad7,2"]) return @"iPad Pro 12.9-inch 2";
  if ([phoneModel isEqualToString:@"iPad7,3"] ||
      [phoneModel isEqualToString:@"iPad7,4"]) return @"iPad Pro 10.5-inch";
  
  if ([phoneModel isEqualToString:@"iPad2,5"] ||
      [phoneModel isEqualToString:@"iPad2,6"] ||
      [phoneModel isEqualToString:@"iPad2,7"]) return @"iPad mini";
  if ([phoneModel isEqualToString:@"iPad4,4"] ||
      [phoneModel isEqualToString:@"iPad4,5"] ||
      [phoneModel isEqualToString:@"iPad4,6"]) return @"iPad mini 2";
  if ([phoneModel isEqualToString:@"iPad4,7"] ||
      [phoneModel isEqualToString:@"iPad4,8"] ||
      [phoneModel isEqualToString:@"iPad4,9"]) return @"iPad mini 3";
  if ([phoneModel isEqualToString:@"iPad5,1"] ||
      [phoneModel isEqualToString:@"iPad5,2"]) return @"iPad mini 4";
  
  if ([phoneModel isEqualToString:@"iPod1,1"]) return @"iTouch";
  if ([phoneModel isEqualToString:@"iPod2,1"]) return @"iTouch2";
  if ([phoneModel isEqualToString:@"iPod3,1"]) return @"iTouch3";
  if ([phoneModel isEqualToString:@"iPod4,1"]) return @"iTouch4";
  if ([phoneModel isEqualToString:@"iPod5,1"]) return @"iTouch5";
  if ([phoneModel isEqualToString:@"iPod7,1"]) return @"iTouch6";
  
#ifdef  DEBUG
  NSLog(@"NOTE: Unknown device type: %@", phoneModel);
#endif
  return [NSString stringWithFormat:@"Apple#%@",phoneModel];
}

+ (NSString *)GJ_getIMSI{
  
  CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
  
  CTCarrier *carrier = [info subscriberCellularProvider];
  
  NSString *mcc = [carrier mobileCountryCode];
  NSString *mnc = [carrier mobileNetworkCode];
  
  NSString *imsi = [NSString stringWithFormat:@"%@%@", mcc, mnc];
  
  return imsi;
}
+ (NSString *)GJ_getGateWay{
  NSString *address = @"error";
  struct ifaddrs *interfaces = NULL;
  struct ifaddrs *temp_addr = NULL;
  int success = 0;
  
  // retrieve the current interfaces - returns 0 on success
  success = getifaddrs(&interfaces);
  if (success == 0) {
    temp_addr = interfaces;
    while(temp_addr != NULL) {
      if(temp_addr->ifa_addr->sa_family == AF_INET) {
        // Check if interface is en0 which is the wifi connection on the iPhone
        if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
        {
          address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
          //                    NSLog(@"本机地址：%@",address);
          
          //routerIP----192.168.1.255 广播地址
          //                    NSLog(@"广播地址：%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)]);
          
          //--192.168.1.106 本机地址
          //                    NSLog(@"本机地址：%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]);
          
          //--255.255.255.0 子网掩码地址
          //                    NSLog(@"子网掩码地址：%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)]);
          
          //--en0 接口
          //  en0       Ethernet II    protocal interface
          //  et0       802.3             protocal interface
          //  ent0      Hardware device interface
          //                    NSLog(@"接口名：%@",[NSString stringWithUTF8String:temp_addr->ifa_name]);
        }
      }
      temp_addr = temp_addr->ifa_next;
    }
  }
  
  freeifaddrs(interfaces);
  in_addr_t i = inet_addr([address cStringUsingEncoding:NSUTF8StringEncoding]);
  in_addr_t* x = &i;
  unsigned char *s = getdefaultgateway(x);
  NSString *ip=[NSString stringWithFormat:@"%d.%d.%d.%d",s[0],s[1],s[2],s[3]];
  free(s);
  return ip;
}



+ (NSString *)GJ_getUUID {
  NSString *UUIDString = @"";
  NSDictionary *UUID_Dict = (NSDictionary *)[GJKeyChainManager load:KEY_UUID_DATA];
  if ([UUID_Dict.allKeys containsObject:KEY_UUID_TEXT]) {
    UUIDString = UUID_Dict[KEY_UUID_TEXT];
  }else {
    //没有就获取
    UUIDString = [UIDevice currentDevice].identifierForVendor.UUIDString;
    //保存
    [GJKeyChainManager save:KEY_UUID_DATA data:@{KEY_UUID_TEXT:UUIDString}];
  }
  return UUIDString;
}


+ (void)sendNotificationForRNEventEmitterWithActionKey:(NSString *)actionKey parameter:(id)parameter{
  
  [[NSNotificationCenter defaultCenter] postNotificationName:GJKGJCommonEmitterNotification object:nil userInfo:@{
    @"actionKey":actionKey,
    @"parameter":parameter
  }];
}

+ (BOOL)GJ_isNull:(NSString *)str{
     if ([str isKindOfClass:[NSNull class]] || [str isEqual:[NSNull null]] || str == nil) {
         return NO;
     }else {
         return YES;
     }
}


/**
判断手机中sim卡数量

@return 返回值 int 个数
*/
+ (int)SimCardNumInPhone {
     CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
     if (@available(iOS 12.0, *)) {
          NSDictionary *ctDict = networkInfo.serviceSubscriberCellularProviders;
          if ([ctDict allKeys].count > 1) {
               NSArray *keys = [ctDict allKeys];
               CTCarrier *carrier1 = [ctDict objectForKey:[keys firstObject]];
               CTCarrier *carrier2 = [ctDict objectForKey:[keys lastObject]];
               if (carrier1.mobileCountryCode.length && carrier2.mobileCountryCode.length) {
                    return 2;
               }else if (!carrier1.mobileCountryCode.length && !carrier2.mobileCountryCode.length) {
                    return 0;
               }else {
                    return 1;
               }
          }else if ([ctDict allKeys].count == 1) {
               NSArray *keys = [ctDict allKeys];
               CTCarrier *carrier1 = [ctDict objectForKey:[keys firstObject]];
               if (carrier1.mobileCountryCode.length) {
                    return 1;
               }else {
                    return 0;
               }
          }else {
               return 0;
          }
     }else {
          CTCarrier *carrier = [networkInfo subscriberCellularProvider];
          NSString *carrier_name = carrier.mobileCountryCode;
          if (carrier_name.length) {
               return 1;
          }else {
               return 0;
          }
     }
}





/// 图片压缩
/// @param image 需要压缩的图片
/// @param maxLength 文件最大大小    signImage = [self compressImage:signImage toByte:10110];
+ (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImagePNGRepresentation(image);
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImagePNGRepresentation(image);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImagePNGRepresentation(image);
    }
    
    return resultImage;
}


@end
